package com.dylan.历史.多线程.并发编程的艺术.编程基础;

import com.dylan.历史.util.LogUtil;
import com.dylan.历史.util.SleepUtils;

import java.util.Random;

/**
 * Created by Dylan on 2018/9/18.
 */
public class join的使用 {

    /**
     * 在threadA中执行了threadB.join()方法，则threadA等待threadB线程终止之后才从threadB.join()方法返回
     *
     * 下面每个线程都执行了前驱线程的join()方法，则每个线程需要前驱线程执行完毕后才从join()方法返回,即前驱线程结束后本线程才能结束
     */
    public static void main(String[] args) {
        Domino predecessor = null;
        for (int i = 0; i < 10; i++) {
            Domino curr = new Domino(predecessor);
            curr.start();
            predecessor = curr;
        }
    }

    private static class Domino extends Thread {
        private Domino predecessor;

        public Domino(Domino predecessor) {
            this.predecessor = predecessor;
        }

        @Override
        public void run() {
            if (predecessor != null) {
                try {
                    SleepUtils.milliseconds(new Random().nextInt(5000));
                    // 等待前驱线程执行结束
                    predecessor.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            LogUtil.info("运行结束");
        }
    }
}
